package com.baomidou.springmvc.controller;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.springmvc.common.result.RequestDTO;
import com.baomidou.springmvc.common.result.ResponseCodeEnum;
import com.baomidou.springmvc.common.result.ServerResponse;
import com.baomidou.springmvc.model.system.SysUser;
import com.baomidou.springmvc.service.system.ISysUserService;

@Controller
@RequestMapping("sysUser")
public class SysUserController {

	@Autowired
	private ISysUserService sysUserService;
	
	@ResponseBody
	@RequestMapping("/add")
	public ServerResponse<SysUser> addSysUser(@RequestBody RequestDTO requestDTO){
		String name = requestDTO.getParam("name");
		String pwd = requestDTO.getParam("pwd");
		SysUser sys = new SysUser();
		sys.setName(name);
		sys.setPwd(DigestUtils.md5Hex(pwd));
		sys.setCreatetime(new Date());
		sys.setUpdatetime(new Date());
		sys.setLasttime(new Date());
		if(sysUserService.insert(sys)) {
			return ServerResponse.createBySuccess("注册成功", sys);
		}
		return ServerResponse.createByErrorMessage("注册失败");
	}
	
	@ResponseBody
	@RequestMapping(value="/login",method = RequestMethod.POST)
	public ServerResponse<SysUser> login( @RequestBody RequestDTO requestDTO) {
		String name = requestDTO.getParam("name");
		String pwd = requestDTO.getParam("pwd");
		String pwdMd5 = DigestUtils.md5Hex(pwd);
		SysUser sys = sysUserService.findSysByName(name);
		//用户不存在
		if(null==sys) {
			return ServerResponse.createByErrorCodeMessage(ResponseCodeEnum.USERNAME_ERROR.getCode(), ResponseCodeEnum.USERNAME_ERROR.getDesc());
		}
		//密码错误
		if(!(sys.getPwd().equals(pwdMd5))) {
			return ServerResponse.createByErrorCodeMessage(ResponseCodeEnum.PWD_ERROR.getCode(), ResponseCodeEnum.PWD_ERROR.getDesc());
		}
		sys.setLasttime(new Date());
		sysUserService.updateById(sys);
		return ServerResponse.createBySuccessMessage("登录成功");
	}
}
